<template>
    <div style="line-height: 30px;" class="d-flex">
        <!-- 当前路径 -->
        <div style="flex:1;display: flex">
            <div v-if="currentPath === '/'" style="font-weight: 700;font-size: 14px;">全部文件</div>
            <div v-else>
                <el-breadcrumb separator="/" style="line-height: 30px">
                    <el-breadcrumb-item>
                        <router-link to="?path=/">全部文件</router-link>
                    </el-breadcrumb-item>
                    <el-breadcrumb-item v-for="p in currentPathList" :key="p.path">
                        <router-link v-if="p.path" :to="'?path=' + p.path">{{ p.name }}</router-link>
                        <span v-else>{{ p.name }}</span>
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
        </div>

        <div class="d-flex">
                            <span
                                style="margin-right: 10px;color:#999;font-size: 12px;">已全部加载，共{{
                                    fileData.length
                                }}个</span>
            <el-radio-group v-model="display" size="small">
                <el-radio-button label="block">
                    <el-icon :size="16">
                        <svg class="icon" viewBox="0 0 1024 1024" version="1.1"
                             xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M384 128H213.333333a85.333333 85.333333 0 0 0-85.333333 85.333333v170.666667a85.333333 85.333333 0 0 0 85.333333 85.333333h170.666667a85.333333 85.333333 0 0 0 85.333333-85.333333V213.333333a85.333333 85.333333 0 0 0-85.333333-85.333333zM810.666667 128h-170.666667a85.333333 85.333333 0 0 0-85.333333 85.333333v170.666667a85.333333 85.333333 0 0 0 85.333333 85.333333h170.666667a85.333333 85.333333 0 0 0 85.333333-85.333333V213.333333a85.333333 85.333333 0 0 0-85.333333-85.333333zM384 554.666667H213.333333a85.333333 85.333333 0 0 0-85.333333 85.333333v170.666667a85.333333 85.333333 0 0 0 85.333333 85.333333h170.666667a85.333333 85.333333 0 0 0 85.333333-85.333333v-170.666667a85.333333 85.333333 0 0 0-85.333333-85.333333zM810.666667 554.666667h-170.666667a85.333333 85.333333 0 0 0-85.333333 85.333333v170.666667a85.333333 85.333333 0 0 0 85.333333 85.333333h170.666667a85.333333 85.333333 0 0 0 85.333333-85.333333v-170.666667a85.333333 85.333333 0 0 0-85.333333-85.333333z"
                                p-id="2910"></path>
                        </svg>
                    </el-icon>
                </el-radio-button>
                <el-radio-button label="list">
                    <el-icon :size="16">
                        <svg class="icon" viewBox="0 0 1024 1024" version="1.1"
                             xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M146.285714 749.714286v109.714285c0 9.728-8.557714 18.285714-18.285714 18.285715h-109.714286a18.797714 18.797714 0 0 1-18.285714-18.285715v-109.714285c0-9.728 8.557714-18.285714 18.285714-18.285715h109.714286c9.728 0 18.285714 8.557714 18.285714 18.285715z m0-219.428572v109.714286c0 9.728-8.557714 18.285714-18.285714 18.285714h-109.714286a18.797714 18.797714 0 0 1-18.285714-18.285714v-109.714286c0-9.728 8.557714-18.285714 18.285714-18.285714h109.714286c9.728 0 18.285714 8.557714 18.285714 18.285714z m0-219.428571v109.714286c0 9.728-8.557714 18.285714-18.285714 18.285714h-109.714286a18.797714 18.797714 0 0 1-18.285714-18.285714v-109.714286c0-9.728 8.557714-18.285714 18.285714-18.285714h109.714286c9.728 0 18.285714 8.557714 18.285714 18.285714z m877.714286 438.857143v109.714285c0 9.728-8.557714 18.285714-18.285714 18.285715h-768a18.797714 18.797714 0 0 1-18.285715-18.285715v-109.714285c0-9.728 8.557714-18.285714 18.285715-18.285715h768c9.728 0 18.285714 8.557714 18.285714 18.285715zM146.285714 91.428571v109.714286c0 9.728-8.557714 18.285714-18.285714 18.285714h-109.714286a18.797714 18.797714 0 0 1-18.285714-18.285714v-109.714286c0-9.728 8.557714-18.285714 18.285714-18.285714h109.714286c9.728 0 18.285714 8.557714 18.285714 18.285714z m877.714286 438.857143v109.714286c0 9.728-8.557714 18.285714-18.285714 18.285714h-768a18.797714 18.797714 0 0 1-18.285715-18.285714v-109.714286c0-9.728 8.557714-18.285714 18.285715-18.285714h768c9.728 0 18.285714 8.557714 18.285714 18.285714z m0-219.428571v109.714286c0 9.728-8.557714 18.285714-18.285714 18.285714h-768a18.797714 18.797714 0 0 1-18.285715-18.285714v-109.714286c0-9.728 8.557714-18.285714 18.285715-18.285714h768c9.728 0 18.285714 8.557714 18.285714 18.285714z m0-219.428572v109.714286c0 9.728-8.557714 18.285714-18.285714 18.285714h-768a18.797714 18.797714 0 0 1-18.285715-18.285714v-109.714286c0-9.728 8.557714-18.285714 18.285715-18.285714h768c9.728 0 18.285714 8.557714 18.285714 18.285714z"></path>
                        </svg>
                    </el-icon>
                </el-radio-button>
            </el-radio-group>
        </div>
    </div>
    <div class="display-type-list" v-if="display == 'list'">
        <el-table :data="fileData" style="width: 100%">
            <el-table-column type="selection"/>
            <el-table-column label="名称">
                <!-- 自定义单元格内容 -->
                <template #default="file">
                    <div class="list-file-info">
                        <FileIcon class="list-file-icon" style="width: 40px;" :file="file.row"
                                  :ext="file.row.type"/>
                        <span class="list-file-name">{{ file.row.name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="200"/>
            <el-table-column prop="size" label="大小" width="200">
                <template #default="file">
                    <span class="list-file-size">{{ formatSize(file.row.size) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" width="200">
                <template #default="file">
                    <span class="list-file-time">{{ formatDate(file.row.createTime, 'YYYY-MM-DD HH:mm') }}</span>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="display-type-block" v-else>
        <el-row :gutter="20">
            <el-col :xs="12" :sm="6" :md="4" :lg="3" :xl="2" v-for="(file, index) in fileData"
                    :key="index">
                <file-block-item :file="file"
                                 @contextmenu.prevent.stop="$refs.fileMenu.showMenu($event,file)"/>
            </el-col>
        </el-row>
    </div>
    <!-- 右键菜单 -->
    <context-menu class="file-cxt-menu" element-id="myMenu1" ref="fileMenu" :options="fileMenuOption"
                  @option-clicked="fileMenuClick"/>
    <!-- 新建目录 -->
    <el-dialog v-model="createFolder.visible" title="新建文件夹" width="500px">
        <div>
            <el-input placeholder="请输入文件夹名称" v-model="createFolder.value"/>
            <div style="color: red;height: 30px;line-height: 30px;">{{ createFolder.message }}</div>
        </div>
        <template #footer>
            <!--                将此模板的内容指定插入到footer的位置-->
            <div class="dialog-footer">
                <el-button @click="createFolder.visible = false">取消</el-button>
                <el-button type="primary" :loading="createFolder.loading" @click="handleCreateFolder">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 分享 -->
    <el-dialog v-model="share.visible" title="分享文件" width="600px">
        <div class="share-create-dialog">
            <div v-if="share.showResult">
                <h3 style="margin-bottom: 10px;">分享成功</h3>
                <el-input v-model="share.shareData" />
            </div>
            <div v-else>
                <h2>{{ share.current?.name }}</h2>
                <div class="live d-flex item">
                    <div class="title">有效期:</div>
                    <div class="content">
                        <el-radio-group v-model="share.live">
                            <el-radio-button label="1">1天</el-radio-button>
                            <el-radio-button label="7">7天</el-radio-button>
                            <el-radio-button label="30">30天</el-radio-button>
                            <el-radio-button label="-1">长期有效</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
                <div class="password d-flex item">
                    <div class="title">提取码:</div>
                    <div class="content">
                        <el-radio-group v-model="share.password">
                            <el-radio-button label="yes">需要</el-radio-button>
                            <el-radio-button label="no">不需要</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <span style="color: #999;font-size: 12px;float: left;">配合净网行动, 网盘严厉打击色情低俗等不良信息的传播行为</span>
                <el-button type="primary" v-if="share.showResult">关闭</el-button>
                <el-button v-else type="primary" :loading="share.loading" @click="handleCreateShare">创建分享</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import {ArrowDown, Grid, FolderAdd, Search} from '@element-plus/icons-vue'
import FileIcon from "../components/FileIcon.vue";
import {dayjs, ElMessage, ElMessageBox} from 'element-plus'
import api from "../service/api";
import qs from "qs";
import FileBlockItem from "../components/FileBlockItem.vue";
import strings from "../service/strings";

export default {
    name: "All",
    data() {
        return {

            display: 'block',
            /**
             * @var {FileItem[]}
             */
            fileData: [],
            currentPath: '/',
            fileMenuOption: [
                {
                    name: '打开',
                    slug: 'open',
                },
                {
                    name: '下载',
                    slug: 'download',
                },
                {
                    name: '分享',
                    slug: 'share',
                },
                {
                    type: 'divider',
                },
                {
                    name: '复制',
                    slug: 'copy',
                },
                {
                    name: '移动',
                    slug: 'move',
                },
                {
                    name: '重命名',
                    slug: 'rename',
                },
                {
                    type: 'divider',
                },
                {
                    name: '删除',
                    slug: 'delete',
                },
            ],
            createFolder: {
                visible: false,
                value: '',
                loading: false,
                message: ''
            },
            share: {
                /**
                 * @var {FileItem}
                 */
                current: null,
                visible: false,
                loading: false,
                /**
                 * @var {ShareInfo}
                 */
                info: null,
                live: 1,
                password: 'yes',
                showResult: false,
                shareData: ''
            }
        }
    },
    watch: {
        '$route'() {
            // console.log(this.$route)
            this.handleHashChange();
        }
    },
    computed: {
        currentPathList() {
            if (this.currentPath == '/') return []
            const arr = this.currentPath.replace(/^\//, '').split('/');
            const pathList = [], last = arr.pop();
            let prefix = '';
            arr.forEach(name => {
                prefix += '/' + name;
                pathList.push({name: name, path: prefix})
            })
            pathList.push({name: last, path: null})
            return pathList;
        }
    },

    components: {FileBlockItem, FileIcon, ArrowDown, Grid, FolderAdd},
    mounted() {
        console.log('记载所有的文件')
        // window.addEventListener('popstate',()=>console.log(location.href))
        // window.addEventListener('hashchange', this.handleHashChange) // 添加监听
        this.handleHashChange();
    },
    unmounted() {
        // window.removeEventListener('hashchange', this.handleHashChange); // 取消监听
    },
    methods: {
        ...strings,
        // 加载目录下的所有文件
        async loadFileByPath(path = '/') {
            this.currentPath = path // 保存了当前的请求路径
            // 调用接口
            try {
                this.fileData = [];
                const list = await api.folder.list(path);
                this.fileData = list;
            } catch (e) {
                ElMessage.error(e.message)
            }
        },
        // 获取获取当前目录路径
        getCurrentPath() {
            const query = this.$route.query;
            const params = qs.parse(query)
            return params.path || '/';
        },
        //记载所有的子文件
        handleHashChange() {
            this.loadFileByPath(this.getCurrentPath()) // 有参数则使用 无参数则根目录
        },
        formatDate(time, format = 'MM-DD') {
            return dayjs(time).format(format);
        },
        formatSize(a, b = 2) {
            if (0 == a) return "0 B";
            let c = 1024, d = b || 2, e = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
                f = Math.floor(Math.log(a) / Math.log(c));
            return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f];
        },
        // 对文件名进行处理
        formatName(name) {
            if (!name || name.length < 15) return name;
            const extIndex = name.lastIndexOf('.'),
                ext = name.substr(extIndex);
            return name.substr(0, (15 - ext.length)) + "**" + ext;
        },
        fileMenuClick(data) {
            const {item, option} = data;
            console.log(data)
            if (option.slug == 'share') {
                // 分享
                this.share.current = item
                // 还原分享的数据
                this.share.info = {}
                this.share.showResult = false
                this.share.visible = true;

            } else if (option.slug == 'rename') {
                this.renameFile(item);
            } else if (option.slug == 'delete') {
                this.deleteFile(item);
            }
        },
        handleCreateShare() {
            this.share.info = {
                title: this.share.current.name,
                fileId: this.share.current.id,
                //1:文件 2：文件夹
                type: this.share.current.type == 'folder' ? 2 : 1,
                password: this.share.password,
                live: this.share.live === '-1' ? -1 : (this.share.live * 24 * 3600),
            }
            api.share.create(this.share.info).then(
                /**
                 *
                 * @param {ShareInfo} ret
                 */
                (ret) => {
                    console.log(ret)
                    this.share.info = ret;
                    this.share.showResult = true
                    this.share.shareData = 'http://localhost:3000/s/' + ret.id + (
                        ret.password ? ' 提取码:' + ret.password : ''
                    )
                }).catch(e => ElMessage.error('分享失败(' + e.message + ')'));
        },
        /**
         *
         * @param {FileItem} file
         */
        renameFile(file) {
            ElMessageBox.prompt('', '请输入新的文件名', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValue: file.name,
                closeOnClickModal: false
            }).then(({value}) => {
                api.file.rename({
                    ...file,
                    name: value
                }).then(() => {
                    file.name = value;
                }).catch();
            }).catch();
        },
        /**
         *
         * @param {FileItem} file
         */
        deleteFile(file) {
            ElMessageBox.confirm(
                '确定要删除选中文件吗？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }
            )
                .then(() => {
                    api.file.delete(file).then(() => this.handleHashChange()).catch();
                }).catch();
        },
        createFolderClick() {
            ElMessageBox.prompt(
                '', '新建文件夹',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    closeOnClickModal: false,
                    // inputPattern:/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
                    inputValidator(value) {
                        return !!value;
                    },
                    inputErrorMessage: '必须填写文件夹名称',
                    inputPlaceholder: '请输入文件夹名称'
                })
                .then(({value}) => {
                    // 此处开始进行创建
                })
                .catch()
        },
        async handleCreateFolder() {
            this.createFolder.message = ''
            if (!this.createFolder.value) {
                this.createFolder.message = '请填写文件夹名称'
                return;
            }
            // 开始新建
            this.createFolder.loading = true;
            try {
                await api.folder.create(this.getCurrentPath(), this.createFolder.value);
                this.createFolder.visible = false;
                this.handleHashChange();
            } catch (e) {
                this.createFolder.message = e.message;
            } finally {
                this.createFolder.loading = false // 取消loading
            }

        }
    }
}
</script>

<style scoped>
.list-file-info {
    display: flex;
    line-height: 40px;
    height: 40px;
}

.list-file-icon {
    width: 40px;
    display: flex;
    align-items: center;
}

.list-file-name {
    margin-left: 5px;
}
</style>